package com.dailyblue.project.smbms.alibaba.goods.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dailyblue.project.smbms.alibaba.commons.bean.Goods;
import com.dailyblue.project.smbms.alibaba.commons.util.JsonResult;
import com.dailyblue.project.smbms.alibaba.commons.util.JwtConfig;
import com.dailyblue.project.smbms.alibaba.commons.util.ResultTool;
import com.dailyblue.project.smbms.alibaba.goods.feign.ProviderFeign;
import com.dailyblue.project.smbms.alibaba.goods.mapper.GoodsMapper;
import com.dailyblue.project.smbms.alibaba.goods.service.GoodsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

@Service
@Slf4j
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements GoodsService {
    @Resource
    private ProviderFeign providerFeign;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Cacheable(cacheNames = "findAllGoods", key = "0")
    public JsonResult findAllGoods() {
        List<Goods> list = list();
        list.forEach(e -> {
            int providerId = e.getProviderId();
            log.info("获取id:{}的数据", providerId);
            JsonResult json = providerFeign.findById(providerId);
            log.info("数据是:{}", json);
            e.setProvider(json);
        });
        return ResultTool.success(list);
    }

    @Override
    public JsonResult addCart(HttpServletRequest request, Integer goodsId) {
        String token = request.getHeader("token");
        int userId = Integer.parseInt(JwtConfig.parseJWT(token).get("id").toString());
        HashOperations<String, String, String> hash = stringRedisTemplate.opsForHash();
        // 这个userId用户只有没有存放过这个goodsId商品
        boolean b = hash.hasKey("USER:" + userId, goodsId + "");
        if (b) {
            // 有这个商品
            hash.increment("USER:" + userId, goodsId + "", 1);
        } else {
            // 没有这个商品
            hash.put("USER:" + userId, goodsId + "", 1 + "");
        }
        return ResultTool.success();
    }

    @Override
    public JsonResult showCart(HttpServletRequest request) {
        String token = request.getHeader("token");
        int userId = Integer.parseInt(JwtConfig.parseJWT(token).get("id").toString());
        HashOperations<String, String, String> hash = stringRedisTemplate.opsForHash();
        // 获取到这个用户的所有购物车
        Map<String, String> map = hash.entries("USER:" + userId);
        List<Goods> list = new ArrayList<>();
        AtomicReference<Double> total = new AtomicReference<>((double) 0);
        map.forEach((k, v) -> {
            int goodsId = Integer.parseInt(k);
            int cartNum = Integer.parseInt(v);
            Goods goods = baseMapper.selectById(goodsId);
            goods.setCartNum(cartNum);
            goods.setProvider(providerFeign.findById(goods.getProviderId()));
            goods.setTotal(goods.getGoodsPrice() * goods.getCartNum());
            total.updateAndGet(v1 -> (v1 + goods.getTotal()));
            list.add(goods);
        });
        return ResultTool.success(list, total.toString());
    }

    @Override
    public JsonResult removeCart(HttpServletRequest request, Integer goodsId) {
        String token = request.getHeader("token");
        int userId = Integer.parseInt(JwtConfig.parseJWT(token).get("id").toString());
        HashOperations<String, String, String> hash = stringRedisTemplate.opsForHash();
        hash.delete("USER:" + userId + "", goodsId + "");
        return showCart(request);
    }

    @Override
    public JsonResult updateCart(HttpServletRequest request, Integer goodsId, Integer newNum) {
        String token = request.getHeader("token");
        int userId = Integer.parseInt(JwtConfig.parseJWT(token).get("id").toString());
        HashOperations<String, String, String> hash = stringRedisTemplate.opsForHash();
        hash.put("USER:" + userId, goodsId + "", newNum + "");
        return showCart(request);
    }
}
